import Classdemo.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args) {
        try {
            //创建类的实例
            Class<?> studenClass = Class.forName("Classdemo.Student");
            Student student = (Student) studenClass.newInstance();
            //获取路劲名字
            String str = studenClass.getName();
            System.out.println(str);
            System.out.println(student.age);
            //反射私有成员变量并进行修改
            Field field = studenClass.getDeclaredField("name");
            field.setAccessible(true);
            field.set(student, "xiaoming");
            System.out.println(student);
            //反射私有成员方法并进行修改
            Method method = studenClass.getDeclaredMethod("function", String.class);
            method.setAccessible(true);
            method.invoke(student, "a");
            //反射私有构造方法并修改
            Constructor<?> constructor =(Constructor<?>) studenClass.getDeclaredConstructor(String.class, int.class);
            constructor.setAccessible(true);
            Student student1 = (Student) constructor.newInstance("zhangsan", 18);
            System.out.println(student);
            System.out.println(student1);

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (SecurityException e) {
            throw new SecurityException(e);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}